﻿/*                              
   Copyright 2011 Nils Kopal, Christopher Krüger, Simone Sauer, Dennis Nolte, Uni Duisburg-Essen

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using Sharebert.OverlayLibrary.API;
using System.Numerics;

namespace Sharebert.OverlayLibrary
{

    /// <summary>
    /// Represents a single peer. A peer has a PeerID, an IP address and a port.
    /// </summary>
    [Serializable]
    public class Peer : IPeer, IEquatable<IPeer>
    {
        public Peer()
        {
        }

        public Peer(PeerID peerId, string ip, int port)
        {
            this.ID = peerId;
            this.IP = ip;
            this.ListenPort = port;
        }

        /// <summary>
        /// Two peers are equal if they have the same IP, port and PeerID.
        /// </summary>
        /// <param name="other">The other peer</param>
        /// <returns>true if peers are equal</returns>
        public bool Equals(IPeer other)
        {
            if (other == null)
            {
                return false;
            }
            if (this.IP == null || other.IP == null || (this.ID == null ^ other.ID == null))
            {
                return false;
            }
            return this.IP.Equals(other.IP) && this.ListenPort == other.ListenPort && this.ID.Equals(other.ID);
        }

        public override int GetHashCode()
        {
            int hashCode = 0;
            if (this.IP != null)
            {
                hashCode = hashCode ^ this.IP.GetHashCode();
            }
            return hashCode ^ this.ListenPort.GetHashCode() ^ this.ID.GetHashCode();
        }

        public override string ToString()
        {
            return this.IP + ":" + this.ListenPort + " (ID: " + this.ID + ")";
        }

        #region Properties

        public PeerID ID { get; set; } 

        public string IP { get; set; }

        public int ListenPort { get; set; }

        #endregion

    }
}
